package auth

import (
	"context"
	"strings"

	"mall/common/globalkey"
	"mall/common/utils/pointy"
	"mall/service/user/model"
	"mall/service/user/rpc/internal/svc"
	"mall/service/user/rpc/types/user"

	"github.com/zeromicro/go-zero/core/logx"
)

type BackendGetUserAuthListLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewBackendGetUserAuthListLogic(ctx context.Context, svcCtx *svc.ServiceContext) *BackendGetUserAuthListLogic {
	return &BackendGetUserAuthListLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

// ##25.04.16##  auth
func (l *BackendGetUserAuthListLogic) BackendGetUserAuthList(in *user.BackendUserAuthListReq) (*user.BackendUserAuthListResp, error) {
	var orderBys []string
	if len(in.OrderBy) > 0 {
		for _, orderBy := range in.OrderBy {
			var order = " ASC"
			if orderBy.Order == "1" {
				order = " DESC"
			}
			if orderBy.Field == "id" {
				orderBys = append(orderBys, model.UserAuthColumns.UserID+order)
			}
			if orderBy.Field == "createdAt" {
				orderBys = append(orderBys, model.UserAuthColumns.CreatedAt+order)
			}
		}
	}

	filterMap := make(map[string]map[string][]any)
	resp := &user.BackendUserAuthListResp{}
	var userIds []any
	if len(in.Ids) > 0 {
		for _, v := range in.Ids {
			userIds = append(userIds, v)
		}
		filterMap[model.UserAuthColumns.UserID] = map[string][]any{
			"in": userIds,
		}
	}

	if in.Status != nil {
		filterMap[model.UserAuthColumns.Status] = map[string][]any{
			"equalTo": {*in.Status},
		}
	} else {
		filterMap[model.UserAuthColumns.Status] = map[string][]any{
			"equalTo": {globalkey.StatusEnabled},
		}
	}

	var orderBy string
	if len(orderBys) > 0 {
		orderBy = strings.Join(orderBys, ",")
	} else {
		orderBy = model.UserAuthColumns.UserID + " DESC"
	}
	res, _, err := l.svcCtx.User.GetAuthList(l.ctx, model.M{
		"page":     int64(in.Page),
		"pageSize": int64(in.PageSize),
		"orderBy":  orderBy,
	}, -1, filterMap)
	if err != nil {
		return nil, err
	}

	if len(res) > 0 {
		for _, v := range res {
			resp.List = append(resp.List, &user.UserAuthInfo{
				Id:         &v.UserAuthID,
				UserId:     &v.UserID,
				Nickname:   &v.Nickname,
				Avatar:     &v.Avatar,
				PlatformId: pointy.GetPointer(uint32(v.PlatformID)),
				Unionid:    &v.Unionid,
				AuthKey:    &v.Openid,
			})
		}
	}

	return resp, nil
}
